package fr.nts.framework.core.service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import fr.nts.framework.core.commun.enumeration.Encoding;

/**
 * Service d'envoi de mail.
 * 
 * @author sco
 */
public class MailSender{

	private static final transient Logger log = LoggerFactory.getLogger(MailSender.class);

    private final static String HTML_MAIL_CONTENT = "text/html; charset=utf-8";
  
    /**
     * Api Spring pour envoyer des mails
     */
	private JavaMailSender mailSender;
	
	
	/**
	 * Permet d'envoyer un email
	 * 
	 * @param from L'expéditeur du mail
	 * @param to Le destinataire du mail
	 * @param content Le contenu du mail
	 * @param subject Le sujet du mail
	 * @param encodingType L'encodage du mail
	 */
	public boolean sendHTMLEmail(final String from,
							     final String to,
							     final String contentTxt,
							     final String subject){
		return sentEmail(from,
						 to,
						 contentTxt,
						 subject,
						 Encoding.UTF8,
						 HTML_MAIL_CONTENT,
						 true);
	}
	
	
	/**
	 * Envoie un email
	 */
	private boolean sentEmail(final String from,
							  final String to,
							  final String contentTxt,
							  final String subject,
							  final Encoding encoding,
							  final String contentType,
							  final boolean multipart){
		MimeMessage message = mailSender.createMimeMessage();
		
		try{
			MimeMessageHelper helper = new MimeMessageHelper(message,
					                                         multipart,
															 encoding.getValue());
			helper.setFrom(from);
			helper.setTo(to);
			helper.setSubject(subject);
			message.setContent(contentTxt,
					           contentType);
			
			log.info("Le mail {} est en cours d'envoi", subject);	
			mailSender.send(message);
		}catch(MessagingException e){
			log.error("Echec dans l'envoi du mail :", e);
			return false;
		}catch(MailException e){
			log.error("Echec dans l'envoi du mail :", e);
			return false;
		}
		
		return true;
	}


	// GETTER / SETTER
	@Required
	public void setMailSender(JavaMailSender mailSender){
		this.mailSender = mailSender;
	}
}